import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:model_viewer_plus/model_viewer_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/components/choosebutton.dart';
import 'package:wayofdressing/components/inmenubutton.dart';
import 'package:wayofdressing/dio/configureDio.dart';
import 'package:wayofdressing/screens/add_outfit_screen.dart';
import 'package:wayofdressing/dio/OutfitDio.dart';
import 'package:wayofdressing/category/outfitcategory.dart';
import 'package:wayofdressing/good_method/formatDate.dart';

class MyDressScreen extends StatefulWidget {
  static final String id = 'mydressscreen';

  @override
  State<MyDressScreen> createState() => _MyDressScreenState();
}

class _MyDressScreenState extends State<MyDressScreen> {
  int threeDNumber = 1;
  int whoisactive1 = 0;
  int whoisactive2 = 0;
  int whoisactive3 = 0;
  bool isAddOutfit = false;
  String description = '无';
  String createTime = '';
  Widget widgetList = Container();

  @override
  void initState() {
    super.initState();
    if (isAdd == true) {
      isAdd = false;
      _getDress();

    }
    if (outfitInformation[outfits[whoisactive1]]!.isNotEmpty) {
      var selectedOutfit =outfitInformation[outfits[whoisactive1]]![whoisactive2];
      description = selectedOutfit['description'] ?? '无';
      createTime = formatDate(DateTime.parse(
          selectedOutfit['createdAt'] ?? DateTime.now().toIso8601String()));
    }
  }

  Future<void> _getDress() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      int userId =
          prefs.getInt('id') ?? 0; // Fetch user ID from SharedPreferences
      for (String item in outfits) {
        Response response = await getOutfitByUserIdAndCategory(
            userId: userId, category: item, dio: dio);

        if (response.data['success'] == true) {
          List<String> names = [];
          List<dynamic> data = response.data['data'];
          outfitInformation[item]?.clear();
          for (dynamic item1 in data) {
            Map<String, dynamic> outfitData = Map<String, dynamic>.from(item1);
            outfitInformation[item]?.add(outfitData);
            names.add(item1['name']);
          }
          outfitNumbers[item] = names;
        } else {
          print('Failed to fetch data for category: $item');
        }
      }
      setState(() {
        if (outfitInformation[outfits[whoisactive1]] != null &&
            whoisactive2 < outfitInformation[outfits[whoisactive1]]!.length) {
          var selectedOutfit =
              outfitInformation[outfits[whoisactive1]]![whoisactive2];
          description = selectedOutfit['description'] ?? '无';
          createTime = formatDate(DateTime.parse(
              selectedOutfit['createdAt'] ?? DateTime.now().toIso8601String()));
        }
      });
    } catch (e) {
      print('Error fetching category data: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffffaf0),
      appBar: AppBar(
        backgroundColor: Color(0xfffffaf0),
        elevation: 0,
        toolbarHeight: 80,
        leadingWidth: 100,
        centerTitle: true,
        title: Text(
          '我的搭配',
          style: TextStyle(
            color: Colors.black,
            fontWeight: FontWeight.bold,
            fontSize: kTopTitleFontSize,
          ),
        ),
        leading: Row(
          children: [
            SizedBox(
              width: 10,
            ),
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Transform.scale(
                scaleX: -1,
                child: Icon(
                  Icons.play_arrow_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black.withOpacity(0.5),
                ),
              ),
            ),
          ],
        ),
        actions: [
          MenuAnchor(
            menuChildren: [
              InMenuButton(
                onPressed: () {},
                text: '删除搭配',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '待开发',
                alignment: Alignment.centerRight,
              ),
            ],
            style: MenuStyle(
              shape: MaterialStateProperty.all(
                RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0),
                ),
              ),
              alignment: Alignment(-3, 0.5),
              padding: MaterialStateProperty.all(EdgeInsets.all(15.0)),
              shadowColor: MaterialStateProperty.all(Colors.transparent),
              backgroundColor: MaterialStateProperty.all(
                Colors.black.withOpacity(0.4),
              ),
            ),
            builder: (BuildContext context, MenuController controller,
                Widget? child) {
              return GestureDetector(
                onTap: () {
                  if (controller.isOpen) {
                    controller.close();
                  } else {
                    controller.open();
                  }
                },
                child: Icon(
                  Icons.keyboard_control_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black,
                ),
              );
            },
          ),
          SizedBox(
            width: 20,
          )
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 30.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        height: 40,
                        decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                              spreadRadius: 2, // 阴影扩展半径
                              blurRadius: 5, // 阴影模糊半径
                              offset: Offset(0, 5), // 阴影偏移量
                            ),
                          ],
                          borderRadius: BorderRadius.circular(25),
                          color: Colors.white,
                        ),
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: outfitNumbers.length,
                          itemBuilder: (context, index) {
                            return chooseButton(
                              isActive: whoisactive1,
                              text: outfits[index],
                              listNumber: index,
                              onPressed: () {
                                setState(() {
                                  whoisactive1 = index;
                                  whoisactive2 = 0;
                                  if (outfitInformation[
                                              outfits[whoisactive1]] !=
                                          null &&
                                      whoisactive2 <
                                          outfitInformation[
                                                  outfits[whoisactive1]]!
                                              .length) {
                                    var selectedOutfit = outfitInformation[
                                        outfits[whoisactive1]]![whoisactive2];
                                    description =
                                        selectedOutfit['description'] ?? '无';
                                    createTime = formatDate(DateTime.parse(
                                        selectedOutfit['createdAt'] ??
                                            DateTime.now().toIso8601String()));
                                  } else {
                                    description = '无';
                                    createTime = '无';
                                  }
                                });
                              },
                            );
                          },
                        ),
                      ),
                    ),
                    // Container(
                    //   height: 36,
                    //   margin: EdgeInsets.only(left: 10),
                    //   decoration: BoxDecoration(
                    //     borderRadius: BorderRadius.circular(25),
                    //     color: Colors.grey[200],
                    //   ),
                    //   child: TextButton(
                    //     onPressed: () {},
                    //     child: Text(
                    //       '管理1',
                    //       style: TextStyle(color: Colors.black),
                    //     ),
                    //   ),
                    // )
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        margin: EdgeInsets.symmetric(vertical: 10),
                        height: 40,
                        decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                              spreadRadius: 2, // 阴影扩展半径
                              blurRadius: 5, // 阴影模糊半径
                              offset: Offset(0, 5), // 阴影偏移量
                            ),
                          ],
                          borderRadius: BorderRadius.circular(25),
                          color: Colors.white,
                        ),
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount:
                              outfitNumbers[outfits[whoisactive1]]?.length,
                          itemBuilder: (context, index) {
                            return chooseButton(
                              isActive: whoisactive2,
                              text:
                                  outfitNumbers[outfits[whoisactive1]]![index],
                              listNumber: index,
                              onPressed: () {
                                setState(() {
                                  whoisactive2 = index;
                                  if (outfitInformation[
                                              outfits[whoisactive1]] !=
                                          null &&
                                      whoisactive2 <
                                          outfitInformation[
                                                  outfits[whoisactive1]]!
                                              .length) {
                                    var selectedOutfit = outfitInformation[
                                        outfits[whoisactive1]]![whoisactive2];
                                    description =
                                        selectedOutfit['description'] ?? '无';
                                    createTime = formatDate(DateTime.parse(
                                        selectedOutfit['createdAt'] ??
                                            DateTime.now().toIso8601String()));
                                  }
                                });
                              },
                            );
                          },
                        ),
                      ),
                    ),
                    // Container(
                    //   height: 36,
                    //   margin: EdgeInsets.only(left: 10),
                    //   decoration: BoxDecoration(
                    //     borderRadius: BorderRadius.circular(25),
                    //     color: Colors.grey[200],
                    //   ),
                    //   child: TextButton(
                    //     onPressed: () {},
                    //     child: Text(
                    //       '管理2',
                    //       style: TextStyle(color: Colors.black),
                    //     ),
                    //   ),
                    // )
                  ],
                ),
              ],
            ),
            Expanded(
              child: Container(
                margin: EdgeInsets.symmetric(vertical: 10),
                decoration: BoxDecoration(
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                        spreadRadius: 2, // 阴影扩展半径
                        blurRadius: 5, // 阴影模糊半径
                        offset: Offset(0, 5), // 阴影偏移量
                      ),
                    ],
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(25)),
                child: Stack(
                  children: <Widget>[
                    Opacity(
                      opacity: threeDNumber == 1 ? 1 : 0,
                      child: IgnorePointer(
                        ignoring: threeDNumber == 1 ? false : true,
                        child: ModelViewer(
                          src: '3dmodels/jeo1.glb',
                          autoRotate: true,
                        ),
                      ),
                    ),
                    Opacity(
                      opacity: threeDNumber == 2 ? 1 : 0,
                      child: IgnorePointer(
                        ignoring: threeDNumber == 2 ? false : true,
                        child: ModelViewer(
                          src: '3dmodels/jeo2.glb',
                          autoRotate: true,
                        ),
                      ),
                    ),
                    Opacity(
                      opacity: threeDNumber == 3 ? 1 : 0,
                      child: IgnorePointer(
                        ignoring: threeDNumber == 3 ? false : true,
                        child: ModelViewer(
                          src: '3dmodels/jeo3.glb',
                          autoRotate: true,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '创建日期:$createTime',
                  style: TextStyle(color: Colors.black, fontSize: 18),
                ),
                SizedBox(
                  height: 10,
                ),
                Text(
                  '描述:$description',
                  style: TextStyle(color: Colors.black, fontSize: 18),
                ),
              ],
            ),
            Center(
              child: Container(
                margin: EdgeInsets.only(bottom: 20),
                child: GestureDetector(
                  onTap: () {
                    if (!isAddOutfit)
                      showModalBottomSheet(
                          isScrollControlled: true,
                          context: context,
                          builder: (context) => AddOutfitScreen()).then((_) {
                        setState(() {
                          isAddOutfit = false;
                          if (isAdd == true) {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => MyDressScreen()),
                            );
                          }
                        });
                      });
                    isAddOutfit = true;
                  },
                  child: Icon(
                    Icons.add_circle_outline_rounded,
                    size: 60,
                    color: Colors.black,
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
